import json
import re
from venv import logger
from flask import jsonify, request
from fuzzywuzzy import process, fuzz
from src.llm_apis.openai_service import call_openai_model
from src.db_models.models import Term
from src.prompts import build_example_prompt


def get_text():
    # 获取前端传来的文本
    data = request.get_json()
    text_input = data.get('text')

    if not text_input:
        return jsonify({"error": "未提供输入文本"}), 400

    return text_input

def get_text_and_model():
    data = request.get_json()
    text_input = data.get('text')
    model_choice = data.get('model')  # 获取选择的模型
    return text_input, model_choice



# def process_model_choice(gen_prompt):
#     """
#     根据用户选择的模型调用相应的处理函数。
#
#     :param model_choice: 用户选择的模型 ("openai" 或 "sparkai")
#     :param gen_prompt: 生成的提示语
#     :return: 模型调用的输出结果
#     """
#     data = request.json
#     model_choice = data.get('model')  # 获取选择的模型
#
#     if model_choice == "openai":
#         return call_openai_model(gen_prompt)
#     elif model_choice == "sparkai":
#         return call_sparkai_model(gen_prompt)
#     else:
#         raise ValueError("Invalid model choice")


def change_format(output):
    try:
        # Clean up the output and format it as a valid JSON string
        formatted_output = re.sub(r'```json|```', '', output).strip()

        # Ensure valid JSON by adding commas between separate objects
        formatted_output = f'{formatted_output.replace("}{", "},{")}'

        # Convert to Python list
        result_list = json.loads(formatted_output)

        return result_list
    except json.JSONDecodeError as e:
        # Log error and return failure response
        logger.error(f"JSONDecodeError: {e}, Output: {formatted_output}")
        return {"error": "解析API返回结果时出错"}, 500


# def extract_diverse_terms_from_text(text_input, terms_list):
#     # 用正则表达式或其他方法来识别术语
#     extracted_terms = []
#     # 将文本拆分为词汇/短语进行匹配
#     words = text_input.split()
#     remaining_text = text_input  # 剩余待匹配的文本
#
#     for word in words:
#         # 查找所有可能的术语匹配
#         # 模糊匹配算法fuzz.ratio
#         matches = process.extract(word, terms_list, scorer=fuzz.partial_ratio, limit=None)
#         # matches = process.extract(word, terms_list, scorer=fuzz.ratio, limit=None)
#         for match in matches:
#             match_term = match[0]
#             match_score = match[1]
#             # 后续可加入接口控制阈值, 实现术语发散
#             if match_score >= 90 and match_term not in extracted_terms:  # 避免重复添加
#                 extracted_terms.append(match_term)
#                 # 从剩余文本中去除已匹配的术语
#                 remaining_text = remaining_text.replace(match_term, "", 1)
#
#     return extracted_terms


def extract_terms_from_text(text_input, terms_list):
    extracted_terms = []
    remaining_text = text_input  # 剩余待匹配的文本

    # 将术语库按长度从长到短排序，确保优先匹配长术语
    terms_list_sorted = sorted(terms_list, key=len, reverse=True)

    for term in terms_list_sorted:
        # 在整段文本中进行精确匹配，找到术语库中出现的术语
        if term in remaining_text:
            # 检查术语是否和文本中的词完全匹配
            extracted_terms.append(term)
            remaining_text = remaining_text.replace(term, "", 1)  # 去掉已匹配术语，避免重复匹配

    return extracted_terms


def delete_bracket(text):
    # 处理返回的JSON字符串，去除开头和结尾的[]，并合并对象
    # 目前发现星火模型传入数据需要以list格式，返回的json需要删除开头结尾[]
    try:
        # 解析输入字符串为JSON对象
        json_data = json.loads(text)

        # 判断是否为列表，合并列表中的所有对象
        if isinstance(json_data, list):
            merged_data = {}
            for item in json_data:
                merged_data.update(item)

            # 返回合并后的JSON数据，并格式化为字符串
            return json.dumps(merged_data, indent=4, ensure_ascii=False)
        else:
            return json.dumps(json_data, indent=4, ensure_ascii=False)

    except json.JSONDecodeError:
        # 如果解析失败，返回原始文本
        return text